import 'package:flutter/material.dart';
import 'package:shirne_dialog/shirne_dialog.dart';

import '../../widgets/list_state_page.dart';
import '../../application.dart';
import '../../models/article_comment_model.dart';
import '../../tbicons.dart';
import '../../utils/api.dart';
import '../../widgets/comment_widget.dart';

class CommentPage extends StatefulWidget {
  final int articleId;
  final String title;

  CommentPage({Key? key, required Map<String, dynamic> arguments})
      : articleId = arguments['article_id'] ?? 0,
        title = arguments['title'] ?? '',
        super(key: key);
  @override
  State<CommentPage> createState() => _CommentPageState();
}

class _CommentPageState
    extends ListStatePage<CommentPage, ArticleCommentModel> {
  String title = '...';
  String commentReplacement = '说点什么...';

  final bool _hasContent = false;
  int replyId = 0;
  late TextEditingController _controller;

  @override
  initState() {
    super.initState();
    if (widget.title.isNotEmpty) title = "${widget.title} 的评论";
    _controller = TextEditingController();
    _controller.addListener(_onTextInput);
  }

  // todo
  _onTextInput() {}

  // 提交评论
  _submitComment() async {
    if (_controller.value.text.isEmpty) {
      MyDialog.toast('请填写评论内容');
      return;
    }
    final result = await Api.post('article/do_comment', {
      'id': widget.articleId,
      'content': _controller.value.text,
      'reply_id': replyId,
    });
    if (result.code == 1) {
      MyDialog.toast(result.message);
      _controller.clear();
    } else {
      if (result.code == 99) {
        MyDialog.confirm(result.message, buttonText: '立即登录', cancelText: '暂不登录')
            .then((value) {
          if (value ?? false) {
            app.route('/login');
          }
        });
      } else {
        MyDialog.toast(result.message);
      }
    }
  }

  Future<bool> _askBack() async {
    final result = await MyDialog.confirm('正在编辑\n是否放弃编辑并退出？');
    return result ?? false;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _hasContent ? _askBack : null,
      child: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: buildListView(),
        resizeToAvoidBottomInset: true,
        floatingActionButtonLocation: const _CenterBottomLocation(),
        floatingActionButton: BottomAppBar(
          child: Row(
            children: [
              const SizedBox(
                width: 10,
              ),
              Expanded(
                child: TextField(
                  controller: _controller,
                  maxLines: 6,
                  minLines: 1,
                  decoration: InputDecoration(
                    hintText: commentReplacement,
                    suffixIcon: IconButton(
                      icon: const Icon(Tbicons.close),
                      onPressed: () {
                        _controller.clear();
                      },
                    ),
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: _submitComment,
                child: const Text('提交'),
              ),
              const SizedBox(
                width: 10,
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  String get apiUrl => 'article/comments';

  @override
  Map<String, dynamic> get requestArgs => {'id': widget.articleId};

  @override
  Widget buildItem(ArticleCommentModel item) {
    return CommentWidget(model: item);
  }

  @override
  ArticleCommentModel transItem(item) {
    return ArticleCommentModel.fromJson(item);
  }
}

class _CenterBottomLocation extends FloatingActionButtonLocation {
  const _CenterBottomLocation();
  @override
  Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
    return Offset(
      0,
      scaffoldGeometry.contentBottom -
          scaffoldGeometry.floatingActionButtonSize.height,
    );
  }
}
